class DataMonitor {
    constructor() {
        this.stocks = this.loadStocks();
        this.updateInterval = null;
        this.init();
    }

    init() {
        this.bindEvents();
        this.renderStocks();
        this.startAutoUpdate();
    }

    bindEvents() {
        const addBtn = document.getElementById('addItemBtn');
        const itemInput = document.getElementById('itemInput');

        addBtn.addEventListener('click', () => this.addItem());

        itemInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.addItem();
            }
        });
    }

    loadStocks() {
        const savedStocks = localStorage.getItem('watchlist');
        const stocks = savedStocks ? JSON.parse(savedStocks) : [];

        // 为没有添加时间的股票设置添加时间
        stocks.forEach(stock => {
            if (!stock.addedTime) {
                stock.addedTime = new Date().toISOString();
            }
        });

        return stocks;
    }

    saveStocks() {
        localStorage.setItem('watchlist', JSON.stringify(this.stocks));
    }

    async addItem() {
        const input = document.getElementById('itemInput');
        const errorMessage = document.getElementById('errorMessage');
        const itemCode = input.value.trim();

        if (!itemCode) {
            errorMessage.textContent = '请输入代码或名称';
            return;
        }

        // 检查是否已存在
        if (this.stocks.some(stock => stock.code === itemCode || stock.name === itemCode)) {
            errorMessage.textContent = '该项目已在监控中';
            return;
        }

        try {
            // 显示加载状态
            errorMessage.innerHTML = '<span class="loading"></span>正在获取数据...';

            // 获取信息
            const stockInfo = await this.fetchStockInfo(itemCode);

            if (stockInfo) {
                stockInfo.addedTime = new Date().toISOString();

                this.stocks.push(stockInfo);
                this.saveStocks();
                this.renderStocks();
                this.updateStats();

                // 清空输入
                input.value = '';
                errorMessage.textContent = '';
            } else {
                errorMessage.textContent = '未找到该项目，请检查代码或名称';
            }
        } catch (error) {
            console.error('添加项目失败:', error);
            errorMessage.textContent = '获取数据失败，请重试';
        }
    }

    async fetchStockInfo(stockCode) {
        try {
            console.log('正在搜索标的:', stockCode);

            // 只使用真实API，不再使用模拟数据
            const realData = await this.fetchRealStockData(stockCode);
            if (realData) {
                console.log('成功获取真实数据:', realData);
                return realData;
            }

            console.log('未找到标的数据');
            return null;
        } catch (error) {
            console.error('获取标的信息失败:', error);
            return null;
        }
    }

    async fetchRealStockData(stockCode) {
        try {
            // 前端现在直接发送原始代码，让服务器处理格式转换
            let code = stockCode.trim();
            console.log('请求API路径:', `/api/stock/${code}`);

            // 使用本地代理服务器获取真实数据
            const response = await fetch(`/api/stock/${code}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            console.log('API响应状态:', response.status);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            console.log('API返回结果:', result);

            // 处理非交易时间响应 - 添加股票时仍应返回基本信息
            if (result.isNonTradingHours) {
                console.log('当前为非交易时间，但仍返回股票基本信息');
                // 即使是非交易时间，也应该返回股票的基本信息用于添加到监控列表
                if (result.success && result.data) {
                    const data = result.data;
                    return {
                        code: data.code,
                        name: data.name,
                        price: data.price.toFixed(2),
                        change: data.change.toFixed(2),
                        changePercent: data.changePercent.toFixed(2),
                        lastUpdate: data.updateTime
                    };
                }
                return null;
            }

            if (result.success && result.data) {
                const data = result.data;
                console.log('解析后股票数据:', {
                    code: data.code,
                    name: data.name,
                    price: data.price,
                    change: data.change,
                    changePercent: data.changePercent
                });

                return {
                    code: data.code,
                    name: data.name,
                    price: data.price.toFixed(2),
                    change: data.change.toFixed(2),
                    changePercent: data.changePercent.toFixed(2),
                    lastUpdate: data.updateTime
                };
            }

            console.log('API返回成功但无数据');
            return null;
        } catch (error) {
            console.error('获取真实股票数据失败:', error);
            return null;
        }
    }

    async updateIndexData() {
        try {
            // 并行获取两个指数的数据
            const [shData, cyData] = await Promise.all([
                this.fetchIndexData('sh000001'),
                this.fetchIndexData('sz399006')
            ]);

            if (shData) {
                this.displayIndexData('sh', shData);
            }
            if (cyData) {
                this.displayIndexData('cy', cyData);
            }

          } catch (error) {
            console.error('更新指数数据失败:', error);
        }
    }

    async fetchIndexData(indexCode) {
        try {
            const response = await fetch(`/api/stock/${indexCode}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();

            if (result.success && result.data) {
                const data = result.data;
                return {
                    name: data.name,
                    price: data.price.toFixed(2),
                    change: data.change.toFixed(2),
                    changePercent: data.changePercent.toFixed(2)
                };
            }

            return null;
        } catch (error) {
            console.error(`获取指数${indexCode}数据失败:`, error);
            return null;
        }
    }

    displayIndexData(type, data) {
        const valueElement = document.getElementById(`${type}IndexValue`);
        const changeElement = document.getElementById(`${type}IndexChange`);

        if (!valueElement || !changeElement) return;

        const isPositive = parseFloat(data.changePercent) >= 0;
        const changeText = `${isPositive ? '+' : ''}${data.changePercent}%`;

        valueElement.textContent = data.price;
        changeElement.textContent = changeText;
        changeElement.className = `index-change ${isPositive ? 'positive' : 'negative'}`;
    }

    async updateStockData() {
        if (this.stocks.length === 0) return;

        try {
            // 并行更新所有数据
            const updatePromises = this.stocks.map(async (stock) => {
                const updatedData = await this.fetchStockInfo(stock.code);
                if (updatedData) {
                    // 更新股票信息，但保持添加时间
                    Object.assign(stock, updatedData);
                    stock.addedTime = stock.addedTime; // 保持原有的添加时间
                }
            });

            await Promise.all(updatePromises);

            this.saveStocks();
            this.renderStocks();
            this.updateStats();
        } catch (error) {
            console.error('更新数据失败:', error);
        }
    }

    removeItem(code) {
        this.stocks = this.stocks.filter(stock => stock.code !== code);
        this.saveStocks();
        this.renderStocks();
        this.updateStats();
    }

    renderStocks() {
        const itemsList = document.getElementById('itemsList');
        const emptyState = document.getElementById('emptyState');

        if (this.stocks.length === 0) {
            itemsList.innerHTML = '';
            emptyState.style.display = 'block';
            return;
        }

        emptyState.style.display = 'none';

        itemsList.innerHTML = `
            <div class="items-grid">
                ${this.stocks.map(stock => this.renderStockCard(stock)).join('')}
            </div>
        `;
    }

    renderStockCard(stock) {
        const isPositive = parseFloat(stock.changePercent) >= 0;
        const cardClass = isPositive ? 'positive' : 'negative';

        return `
            <div class="item-card ${cardClass}">
                <div class="stock-info">
                    <div class="stock-details">
                        <div class="item-name">${stock.name}</div>
                        <div class="item-code">${stock.code}</div>
                    </div>
                    <div class="stock-price">
                        <div class="item-price">¥${stock.price}</div>
                        <div class="item-change">
                            <div class="change-value">${isPositive ? '+' : ''}${stock.change}</div>
                            <div class="change-percent">${isPositive ? '+' : ''}${stock.changePercent}%</div>
                        </div>
                    </div>
                </div>
                <div class="item-actions">
                    <button class="kline-btn" onclick="portfolio.showKLine('${stock.code}', '${stock.name}')" title="查看K线图">📈</button>
                    <button class="remove-btn" onclick="portfolio.removeItem('${stock.code}')">×</button>
                </div>
            </div>
        `;
    }

    updateStats() {
        const totalChangeElement = document.getElementById('totalChange');
        const updateTimeElement = document.getElementById('updateTime');

        if (this.stocks.length === 0) {
            totalChangeElement.textContent = '0.00%';
            updateTimeElement.textContent = '--:--:--';
            return;
        }

        // 计算平均涨跌幅
        const totalChangePercent = this.stocks.reduce((sum, stock) => {
            return sum + parseFloat(stock.changePercent);
        }, 0);

        const avgChangePercent = totalChangePercent / this.stocks.length;
        const isPositive = avgChangePercent >= 0;

        totalChangeElement.textContent = `${isPositive ? '+' : ''}${avgChangePercent.toFixed(2)}%`;
        totalChangeElement.className = `stat-value ${isPositive ? 'positive' : 'negative'}`;

        // 更新时间，并显示交易状态
        const now = new Date();
        const timeString = now.toLocaleTimeString('zh-CN');
        const isTrading = this.isTradingHours();
        const statusText = isTrading ? '交易中' : '休市';
        const statusClass = isTrading ? 'trading' : 'closed';

        updateTimeElement.innerHTML = `${timeString} <span class="market-status ${statusClass}">${statusText}</span>`;
    }

    startAutoUpdate() {
        // 立即更新一次
        this.updateStockData();
        this.updateIndexData();

        // 每2秒更新一次，但只检查交易时间
        this.updateInterval = setInterval(() => {
            if (this.isTradingHours()) {
                this.updateStockData();
                this.updateIndexData();
            }
        }, 2000);
    }

    // 检查当前是否为交易时间 (9:00 - 16:00)
    isTradingHours() {
        const now = new Date();
        const hour = now.getHours();
        const minute = now.getMinutes();
        const currentTime = hour * 60 + minute; // 转换为分钟

        // 交易时间：9:00-16:00 (540 - 960分钟)
        // 周末不交易
        const dayOfWeek = now.getDay(); // 0是周日，6是周六

        return dayOfWeek >= 1 && dayOfWeek <= 5 && currentTime >= 540 && currentTime < 960;
    }

    stopAutoUpdate() {
        if (this.updateInterval) {
            clearInterval(this.updateInterval);
            this.updateInterval = null;
        }
    }

    // K线图相关方法
    showKLine(stockCode, stockName) {
        clearTimeout(this.klineTimeout);

        const container = document.getElementById('klineContainer');
        const title = document.getElementById('klineTitle');
        const loading = document.getElementById('klineLoading');
        const error = document.getElementById('klineError');
        const chart = document.getElementById('klineChart');

        // 设置标题
        title.textContent = `${stockName} (${stockCode})`;

        // 显示容器和加载状态
        container.style.display = 'block';
        loading.style.display = 'block';
        error.style.display = 'none';
        chart.style.display = 'none';

        // 延迟加载，避免鼠标快速移动时频繁请求
        this.klineTimeout = setTimeout(async () => {
            await this.loadKLineData(stockCode);
        }, 300);
    }

    hideKLine() {
        clearTimeout(this.klineTimeout);
        const container = document.getElementById('klineContainer');
        container.style.display = 'none';
    }

    async loadKLineData(stockCode) {
        try {
            // 获取日K线数据
            const response = await fetch(`/api/kline/${stockCode}?period=d&count=30`);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();

            if (result.success && result.data) {
                this.drawKLine(result.data);
            } else {
                this.showKLineError();
            }
        } catch (error) {
            console.error('获取K线数据失败:', error);
            this.showKLineError();
        }
    }

    drawKLine(data) {
        const canvas = document.getElementById('klineCanvas');
        const ctx = canvas.getContext('2d');
        const loading = document.getElementById('klineLoading');
        const chart = document.getElementById('klineChart');

        // 隐藏加载，显示图表
        loading.style.display = 'none';
        chart.style.display = 'block';

        // 清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        if (!data || data.length === 0) {
            this.showKLineError();
            return;
        }

        const padding = 20;
        const chartWidth = canvas.width - padding * 2;
        const chartHeight = canvas.height - padding * 2;

        // 计算价格范围
        const prices = data.map(d => d.close);
        const minPrice = Math.min(...prices);
        const maxPrice = Math.max(...prices);
        const priceRange = maxPrice - minPrice || 1;

        // 绘制K线
        const barWidth = chartWidth / data.length;

        data.forEach((candle, index) => {
            const x = padding + index * barWidth + barWidth / 2;

            // 计算Y坐标
            const openY = padding + chartHeight - ((candle.open - minPrice) / priceRange) * chartHeight;
            const closeY = padding + chartHeight - ((candle.close - minPrice) / priceRange) * chartHeight;
            const highY = padding + chartHeight - ((candle.high - minPrice) / priceRange) * chartHeight;
            const lowY = padding + chartHeight - ((candle.low - minPrice) / priceRange) * chartHeight;

            // 确定颜色
            const isPositive = candle.close >= candle.open;
            const color = isPositive ? '#f44336' : '#4CAF50';

            // 绘制高低线
            ctx.strokeStyle = color;
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(x, highY);
            ctx.lineTo(x, lowY);
            ctx.stroke();

            // 绘制实体
            const bodyHeight = Math.abs(closeY - openY);
            const bodyY = Math.min(openY, closeY);

            ctx.fillStyle = color;
            if (isPositive) {
                // 阳线，空心
                ctx.strokeStyle = color;
                ctx.lineWidth = 1;
                ctx.strokeRect(x - barWidth * 0.3, bodyY, barWidth * 0.6, bodyHeight);
            } else {
                // 阴线，实心
                ctx.fillRect(x - barWidth * 0.3, bodyY, barWidth * 0.6, bodyHeight);
            }
        });

        // 绘制坐标轴
        ctx.strokeStyle = '#ddd';
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(padding, padding);
        ctx.lineTo(padding, canvas.height - padding);
        ctx.lineTo(canvas.width - padding, canvas.height - padding);
        ctx.stroke();
    }

    showKLineError() {
        const loading = document.getElementById('klineLoading');
        const error = document.getElementById('klineError');
        const chart = document.getElementById('klineChart');

        loading.style.display = 'none';
        chart.style.display = 'none';
        error.style.display = 'block';
    }
}

// 初始化应用
const portfolio = new DataMonitor();

// 页面卸载时停止自动更新
window.addEventListener('beforeunload', () => {
    portfolio.stopAutoUpdate();
});